import type {
  ComputeContext,
  CreateCrudOptionsProps,
  CreateCrudOptionsRet,
  ScopeContext,
} from '@fast-crud/fast-crud';

import type { SopIsvKeysModel } from '#/api/devOperation/sop/model/sopIsvKeysModel';

import { ref } from 'vue';

import { $t } from '@vben/locales';

import { compute } from '@fast-crud/fast-crud';
import { Button } from 'ant-design-vue';

import { SopIsvInfoApi } from '#/api/devOperation/sop/sopIsvInfo';
import { ActionEnum, DictEnum } from '#/enums/commonEnum';
import { backendDict } from '#/plugins/fast-crud/common';

type ContextRef = object;

export function createCrudOptions(
  _props: CreateCrudOptionsProps<
    SopIsvKeysModel.SopIsvKeysResultVO,
    ContextRef
  >,
): CreateCrudOptionsRet<SopIsvKeysModel.SopIsvKeysResultVO> {
  const buttonLoading = ref(false);

  async function handleRestPlatformKeys(scope: ScopeContext) {
    buttonLoading.value = true;
    try {
      const result = await SopIsvInfoApi.createKeys({
        keyFormat: scope.form.keyFormat,
      });

      scope.form.publicKeyPlatform = result.publicKey;
      scope.form.privateKeyPlatform = result.privateKey;
    } finally {
      buttonLoading.value = false;
    }
  }

  async function handleResetIsvKeys(scope: ScopeContext) {
    buttonLoading.value = true;
    try {
      const result = await SopIsvInfoApi.createKeys({
        keyFormat: scope.form.keyFormat,
      });

      scope.form.publicKeyIsv = result.publicKey;
      scope.form.privateKeyIsv = result.privateKey;
    } finally {
      buttonLoading.value = false;
    }
  }
  return {
    crudOptions: {
      settings: { viewFormUseCellComponent: false },
      request: {
        addRequest: SopIsvInfoApi.updateKeysRequest,
      },
      actionbar: {
        show: false,
      },
      form: {
        col: { span: 24 },
        // label 宽度
        labelCol: { span: null, style: { minWidth: '150px' } },
        group: {
          type: 'tabs', // tab
          accordion: false, // 手风琴模式
          displayDirective: 'show',
          triggerAreas: ['arrow'],
          groups: {
            basic: {
              header: '基础信息',
              columns: ['isvId', 'appId', 'keyFormat'],
            },
            isv: {
              header: 'ISV公私钥',
              columns: ['publicKeyIsv', 'privateKeyIsv', 'resetIsvKeys'],
            },
            platform: {
              header: '平台公私钥',
              columns: [
                'publicKeyPlatform',
                'privateKeyPlatform',
                'restPlatformKeys',
              ],
            },
          },
        },
      },
      columns: {
        isvId: {
          title: $t('devOperation.sop.sopIsvKeys.isvId'),
          type: 'text',
          form: {
            show: false,
          },
        },
        appId: {
          title: $t('devOperation.sop.sopIsvKeys.appId'),
          type: 'text',
          form: {
            component: {
              readonly: true,
            },
          },
          viewForm: {
            render: ({ form, key }) => {
              return (
                <fs-copyable
                  v-model={
                    form[key as keyof SopIsvKeysModel.SopIsvKeysResultVO]
                  }
                ></fs-copyable>
              );
            },
          },
        },
        keyFormat: {
          title: $t('devOperation.sop.sopIsvKeys.keyFormat'),
          type: 'dict-radio',
          dict: backendDict(DictEnum.SOP_ISV_KEYS_KEY_FORMAT),
          search: { show: true },
        },
        publicKeyIsv: {
          title: $t('devOperation.sop.sopIsvKeys.publicKeyIsv'),
          type: 'textarea',
          form: {
            component: {
              autoSize: { minRows: 2, maxRows: 5 },
            },
            helper: '平台使用，用来校验签名景否正确',
          },
        },
        privateKeyIsv: {
          title: $t('devOperation.sop.sopIsvKeys.privateKeyIsv'),
          type: 'textarea',
          form: {
            component: { autoSize: { minRows: 2, maxRows: 5 } },
            helper: '提供给ISV使用，用来生成签名',
          },
        },
        resetIsvKeys: {
          title: '',
          type: 'text',
          form: {
            colon: false,
            title: '',
            submit: false,
            show: compute((context: ComputeContext) => {
              return context.mode === ActionEnum.ADD;
            }),
            render(scope: ScopeContext) {
              return (
                <Button
                  loading={buttonLoading.value}
                  onClick={() => handleResetIsvKeys(scope)}
                  type="primary"
                >
                  重置ISV秘钥
                </Button>
              );
            },
          },
        },
        publicKeyPlatform: {
          title: $t('devOperation.sop.sopIsvKeys.publicKeyPlatform'),
          type: 'textarea',
          form: {
            component: { autoSize: { minRows: 2, maxRows: 5 } },
            helper: '提供给ISV使用，用来校验签名是否正确',
          },
        },
        privateKeyPlatform: {
          title: $t('devOperation.sop.sopIsvKeys.privateKeyPlatform'),
          type: 'textarea',
          form: {
            component: { autoSize: { minRows: 2, maxRows: 5 } },
            helper: '平台使用，对返回结果生成签名',
          },
        },
        restPlatformKeys: {
          title: '',
          type: 'text',
          form: {
            colon: false,
            title: '',
            submit: false,
            show: compute((context: ComputeContext) => {
              return context.mode === ActionEnum.ADD;
            }),
            render(scope: ScopeContext) {
              return (
                <Button
                  loading={buttonLoading.value}
                  onClick={() => handleRestPlatformKeys(scope)}
                  type="primary"
                >
                  重置平台秘钥
                </Button>
              );
            },
          },
        },
      },
    },
  };
}

export const downloadTemplate = `
请妥善保管以下参数，切勿泄露。

AppId:
{appId}

开发者私钥(用来生成签名):
{privateKeyIsv}

平台公钥(用来校验签名是否正确):
{publicKeyPlatform}

`;
